package com.mi.rof.user.service.impl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mi.rof.entity.*;
import com.mi.rof.entity.enums.ExceptionEnum;
import com.mi.rof.entity.enums.RoleEnum;
import com.mi.rof.entity.vo.UserInfoVo;
import com.mi.rof.user.entity.UserTable;
import com.mi.rof.user.mapper.UserTableMapper;
import com.mi.rof.user.service.UserService;
import com.mi.rof.utils.JwtUtils;
import com.mi.rof.utils.UserThreadLocal;
import com.mi.rof.entity.param.UserParam;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserTableMapper userTableMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result login(UserParam userParam)  {
        String userId = userParam.getUserId();
        if (userId != null) {
            LambdaQueryWrapper<UserTable> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserTable::getUserId, userId);
            UserTable userTable = userTableMapper.selectOne(queryWrapper);
            String userPassword = userParam.getPassword();
            //对userPassword进行md5加密
            String encodedPassword = MD5.create().digestHex(userPassword);
            if (userTable.getPassword().equals(encodedPassword)) {
                //校验通过
                UserInfoVo userInfoVo = new UserInfoVo();
                BeanUtils.copyProperties(userTable, userInfoVo);
                userInfoVo.setUserRole(RoleEnum.getByMsg(userParam.getRole()).getCode());
                String token = JwtUtils.createToken(userInfoVo);
                userInfoVo.setToken(token);
                //放入redis缓存标识状态
                stringRedisTemplate.opsForValue().set(userId, token);
                //设置过期时间
                stringRedisTemplate.expire(userId,  System.currentTimeMillis()+1000 * 60 * 60 *24, TimeUnit.MILLISECONDS);
                //放入threadLocal中
                UserThreadLocal.put(userInfoVo);
                return Result.successResult(token);
            }else{
                throw new SystemException(ExceptionEnum.PASSWORD_ERROR.getCode(), ExceptionEnum.PASSWORD_ERROR.getMsg());
            }
        }
        //不存在抛出异常
        throw new SystemException(ExceptionEnum.USER_NOT_EXIST.getCode(), ExceptionEnum.USER_NOT_EXIST.getMsg());
    }

    @Override
    public UserTable getNormalUser(String userId) {
        UserTable userTable = userTableMapper.selectById(userId);
        if(ObjectUtil.isNull(userTable)){
            throw new SystemException(ExceptionEnum.USER_NOT_EXIST.getCode(), ExceptionEnum.USER_NOT_EXIST.getMsg());
        }
        return userTable;
    }
}
